package com.kou.controller;

import com.alibaba.fastjson.JSONObject;
import com.kou.pojo.Type;
import com.kou.service.TypeService;
import com.kou.service.impl.TypeServiceImpl;
import com.kou.utils.Constants;
import com.kou.utils.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author SteinY
 * @create 2022-03-25 11:17
 * @description:
 */
@WebServlet("/type")
public class TypeServlet extends BaseServlet{
    TypeService typeService = new TypeServiceImpl();
    public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Type> types = typeService.findAll();

        //返回值
        return JSONObject.toJSONString(types);
    }

    public String findAll1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Type> types = typeService.findAll1();

        //返回值
        return JSONObject.toJSONString(types);
    }
    public String update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Type type = typeService.find(Integer.parseInt(id));
        //返回值
        request.setAttribute("type",type);
        return Constants.FORWARD+"admin/updateGoodsType.jsp";
    }

    public String updateGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsParent = request.getParameter("goodsParent");
        String typename = request.getParameter("typename");
        String typeid = request.getParameter("typeid");
        if (StrUtils.empty(goodsParent)){
            Type parent = typeService.find(Integer.parseInt(goodsParent));
            Type type = new Type(Integer.parseInt(typeid),typename,parent.getLevel()+1,parent.getId(),parent.getParentName());
            typeService.update(type);
        }else {
            Type type = new Type(Integer.parseInt(typeid),typename,null,null,null);
            typeService.update(type);
        }

        //返回值
        return Constants.REDIRECT+"admin/showGoodsType.jsp";
    }

}
